package net.oschina.simpleplus.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import net.oschina.simpleplus.entity.Post;
import net.oschina.simpleplus.entity.User;
import net.oschina.simpleplus.ser.PostSer;
import net.oschina.simpleplus.util.StrUtil;

@Controller
@RequestMapping("/post")
public class PostCtrl {
	@Autowired
	private PostSer postSer;
	
	@RequestMapping("/details/{id}/{page}")
	public String details(@PathVariable("id") Integer id, @PathVariable(value= "page", required = false) Integer page, ModelMap mm){
		if(page == null){
			page = 1;
		}
		
		page = Math.max(page, 1);
		
		mm.addAttribute("posts", postSer.findPostsById(id, 1));
		mm.addAttribute("currPostId", id);
		return "details";
	}

	@RequestMapping(value = "/newPost", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> newPost(HttpServletRequest req,@RequestBody String content){
		if(StrUtil.isAnyBlank(content)){
			throw new RuntimeException("不能为空");
		}
		try {
			Post post = StrUtil.toJavaObject(Post.class, content);
			post.setAuthorId(getCurrentUser(req).getId());
			post.setCreateTime(new Date());
			post.setLastUpdateTime(new Date());
			post.setPostId(0);
			
			postSer.insertPost(post);
			return new HashMap<>();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		
	}
	
	
	
	private static User getCurrentUser(HttpServletRequest req){
		User attribute = (User) req.getSession().getAttribute("user");
		if(attribute == null){
			attribute = new User();
			attribute.setId(1);
		}
		return attribute;
	}
}
